<template>
  <view class="activity-list-container">
    
    
    <!-- Tab切换 -->
    <view class="tab-container">
      <view 
        :class="['tab-item', { active: currentTab === 'online' }]"
        @tap="switchTab('online')"
      >
        已上架
      </view>
      <view 
        :class="['tab-item', { active: currentTab === 'offline' }]"
        @tap="switchTab('offline')"
      >
        未上架
      </view>
    </view>

    <!-- 活动列表 -->
    <view class="activity-list">
      <!-- 已上架列表 -->
      <view v-if="currentTab === 'online'" class="list-content">
        <view 
          v-for="(item, index) in onlineActivities" 
          :key="'online-' + index"
          class="activity-card"
          @tap="goToDetail(item.id)"
        >
          <view class="activity-info">
            <view class="activity-title">{{ item.title }}</view>
            <view class="activity-time">{{ item.time }}</view>
          </view>
          <view class="activity-action">
            <button class="btn-download" size="mini" @tap.stop="handleDownload(item.id)">下架</button>
          </view>
        </view>
      </view>

      <!-- 未上架列表 -->
      <view v-else-if="currentTab === 'offline'" class="list-content">
        <view 
          v-for="(item, index) in offlineActivities" 
          :key="'offline-' + index"
          class="activity-card"
          @tap="goToDetail(item.id)"
        >
          <view class="activity-info">
            <view class="activity-title">
              {{ item.title }}
              <text :class="['review-status', item.statusClass]">{{ item.reviewStatus }}</text>
            </view>
            <view class="activity-time">{{ item.time }}</view>
          </view>
          <view class="activity-action">
            <button 
              :class="['btn-action', item.actionClass]" 
              size="mini" 
              @tap.stop="handleAction(item.action, item.id)"
            >
              {{ item.actionText }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 发布活动按钮 -->
    <view class="publish-btn-container">
      <button class="publish-btn" @tap="goToPublish">+发布活动</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
// 当前选中的Tab
const currentTab = ref<'online' | 'offline'>('online');

// 活动数据接口定义
interface ActivityItem {
  id: string;
  title: string;
  time: string;
}

// 已上架活动数据
const onlineActivities = ref<ActivityItem[]>([]);

// 加载已上架活动数据
  const loadOnlineActivities = async () => {
    console.log('开始加载已上架活动数据');
    try {
      console.log('发起API请求: http://localhost:8080/cc/activity/lists');
      const response = await uni.request({
        url: 'http://localhost:8080/cc/activity/lists',
        method: 'GET',
        data: {
          status: 1,
          // 根据数据库表结构，字段名为is_launch而不是isLaunch
          'isLaunch': 0
        }
      });
      
      console.log('API响应状态码:', response.statusCode);
      console.log('API响应数据:', response.data);
      if (response.statusCode === 200 && response.data) {
        const resData = response.data as any;
        console.log('解析后的数据:', resData);
        // 根据API返回的实际数据结构，直接使用resData.rows
        if (resData.rows) {
          // 格式化数据以匹配前端需要的结构
          const formattedData = resData.rows.map((item: any) => ({
            id: item.id,
            title: item.title,
            time: item.time || ''
          }));
          
          // 按照时间降序排序，最新的活动排在前面
          formattedData.sort((a: any, b: any) => {
            return new Date(b.time).getTime() - new Date(a.time).getTime();
          });
          
          console.log('排序后的活动数据:', formattedData);
          onlineActivities.value = formattedData;
        }
      }
    } catch (error) {
      console.error('加载已上架活动失败:', error);
      console.log('错误详情:', error);
      uni.showToast({
      title: '加载失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadOnlineActivities();
  // 页面加载时也加载未上架活动数据，以防用户切换到未上架Tab
  loadOfflineActivities();
});

// 未上架活动数据接口定义
interface OfflineActivityItem extends ActivityItem {
  status: number; // 0：待审核，1：审核通过，2：审核不通过
  reviewStatus: string;
  statusClass: string;
  action: 'publish' | 'delete';
  actionText: string;
  actionClass: string;
}

// 未上架活动数据
const offlineActivities = ref<OfflineActivityItem[]>([]);

// 加载未上架活动数据
const loadOfflineActivities = async () => {
  console.log('开始加载未上架活动数据');
  try {
    // 分两次请求数据：第一次请求isLaunch=1，第二次请求isLaunch=null
    console.log('发起第一次API请求: http://localhost:8080/cc/activity/lists');
    const response1 = await uni.request({
      url: 'http://localhost:8080/cc/activity/lists',
      method: 'GET',
      data: {
          deleted: 0,
          isLaunch: 1
        }
    });
    
    console.log('第一次API响应状态码:', response1.statusCode);
    
    console.log('发起第二次API请求: http://localhost:8080/cc/activity/lists');
    const response2 = await uni.request({
      url: 'http://localhost:8080/cc/activity/lists/launch',
      method: 'GET',
      data: {
          deleted: 0,
        }
    });
    
    console.log('第二次API响应状态码:', response2.statusCode);
    
    // 合并两次请求的数据
    let allRows: any[] = [];
    
    if (response1.statusCode === 200 && response1.data && (response1.data as any).rows) {
      const resData1 = response1.data as any;
      allRows = [...allRows, ...resData1.rows];
    }
    
    if (response2.statusCode === 200 && response2.data && (response2.data as any).rows) {
      const resData2 = response2.data as any;
      allRows = [...allRows, ...resData2.rows];
    }
    
    console.log('合并后的总数据条数:', allRows.length);
    
    // 过滤出deleted为0的数据
    const filteredRows = allRows.filter((row: any) => row.deleted === 0);
    console.log('过滤后的未删除活动数据数量:', filteredRows.length);
        
        // 格式化数据并映射审核状态
        const formattedData = filteredRows.map((item: any) => {
          const status = item.status || 0;
          const reviewStatusMap = {
            0: '待审核',
            1: '审核通过',
            2: '审核不通过'
          };
          const statusClassMap = {
            0: 'status-reviewing',
            1: 'status-approved',
            2: 'status-rejected'
          };
          
          return {
            id: item.id,
            title: item.title,
            time: item.time || '',
            status: status,
            reviewStatus: reviewStatusMap[status as keyof typeof reviewStatusMap] || '待审核',
            statusClass: statusClassMap[status as keyof typeof statusClassMap] || 'status-reviewing',
            action: (status === 1 ? 'publish' : 'delete') as 'publish' | 'delete',
            actionText: status === 1 ? '上架' : '删除',
            actionClass: status === 1 ? 'btn-publish' : 'btn-delete'
          };
        });
        
        // 按照时间降序排序，最新的活动排在前面
        formattedData.sort((a: any, b: any) => {
          return new Date(b.time).getTime() - new Date(a.time).getTime();
        });
        
        console.log('格式化后的未上架活动数据:', formattedData);
        offlineActivities.value = formattedData;
  } catch (error) {
    console.error('加载未上架活动失败:', error);
    console.log('错误详情:', error);
    uni.showToast({
      title: '加载失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 切换Tab
const switchTab = async (tab: 'online' | 'offline') => {
  currentTab.value = tab;
  // 切换Tab时加载对应的数据
  if (tab === 'offline') {
    await loadOfflineActivities();
  }
};

// 跳转到详情页
const goToDetail = async (id: string) => {
  try {
    console.log('开始获取活动详情，活动ID:', id);
    // 显示加载状态
    uni.showLoading({
      title: '加载中...'
    });
    
    // 调用API获取活动详情
    const response = await uni.request({
      url: `http://localhost:8080/cc/activity/${id}`,
      method: 'GET'
    });
    
    uni.hideLoading();
    
    console.log('活动详情API响应状态码:', response.statusCode);
    console.log('活动详情API响应数据:', response.data);
    
    if (response.statusCode === 200 && response.data) {
      const detailData = response.data as any;
      console.log('获取到的活动详情:', detailData);
      
      // 跳转到详情页，并将详情数据通过query传递
      uni.navigateTo({
        url: `/pages/activity/detail?id=${id}&mode=view&data=${encodeURIComponent(JSON.stringify(detailData))}`
      });
    } else {
      console.log('API请求失败或返回数据格式不正确');
      uni.showToast({
        title: '获取详情失败，请稍后重试',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取活动详情失败:', error);
    console.log('错误详情:', error);
    uni.showToast({
      title: '获取详情失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 跳转到发布页面
const goToPublish = () => {
  uni.navigateTo({
    url: '/pages/activity/detail?mode=publish'
  });
};

// 处理下架操作
const handleDownload = async (id: string) => {
  console.log('开始下架操作，活动ID:', id);
  uni.showModal({
    title: '确认下架',
    content: '确定要下架该活动吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          console.log('确认下架，准备调用API');
          // 显示加载状态
          uni.showLoading({
            title: '下架中...'
          });
          
          // 根据数据库表结构，使用正确的字段名
          const updateData = {
            isLaunch: 1,
            id: id
          };
          console.log('发起下架API请求，数据:', updateData);
          const response = await uni.request({
            url: 'http://localhost:8080/cc/activity',
            method: 'PUT',
            data: updateData
          });
          
          uni.hideLoading();
          
          console.log('下架API响应:', response);
          // 更准确地判断成功条件
          if (response.statusCode === 200) {
            uni.showToast({
              title: '下架成功',
              icon: 'success'
            });
            
            console.log('下架成功，准备刷新活动列表');
            // 重新加载已上架活动列表
            await loadOnlineActivities();
            console.log('活动列表已刷新');
          } else {
            console.log('API请求失败或返回数据格式不正确');
            uni.showToast({
              title: '下架失败，请稍后重试',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('下架活动失败:', error);
          console.log('错误详情:', error);
          uni.showToast({
            title: '下架失败，请稍后重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 处理活动操作（上架/删除）
const handleAction = (action: string, id: string) => {
  if (action === 'publish') {
    uni.showModal({
      title: '确认上架',
      content: '确定要上架该活动吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            console.log('确认上架，准备调用API，活动ID:', id);
            // 显示加载状态
            uni.showLoading({
              title: '上架中...'
            });
            
            const updateData = {
              isLaunch: 0,
              id: id
            };
            console.log('发起上架API请求，数据:', updateData);
            const response = await uni.request({
              url: 'http://localhost:8080/cc/activity',
              method: 'PUT',
              data: updateData
            });
            
            uni.hideLoading();
            
            console.log('上架API响应:', response);
            if (response.statusCode === 200) {
              uni.showToast({
                title: '上架成功',
                icon: 'success'
              });
              
              console.log('上架成功，刷新未上架活动列表');
              // 刷新未上架活动列表
              await loadOfflineActivities();
              // 同时刷新已上架活动列表，因为该活动现在应该显示在已上架列表中
              await loadOnlineActivities();
            } else {
              console.log('API请求失败或返回数据格式不正确');
              uni.showToast({
                title: '上架失败，请稍后重试',
                icon: 'none'
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error('上架活动失败:', error);
            console.log('错误详情:', error);
            uni.showToast({
              title: '上架失败，请稍后重试',
              icon: 'none'
            });
          }
        }
      }
    });
  } else if (action === 'delete') {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除该活动吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            console.log('确认删除，准备调用API，活动ID:', id);
            // 显示加载状态
            uni.showLoading({
              title: '删除中...'
            });
            
            const updateData = {
              deleted: 1,
              id: id
            };
            console.log('发起删除API请求，数据:', updateData);
            const response = await uni.request({
              url: 'http://localhost:8080/cc/activity',
              method: 'PUT',
              data: updateData
            });
            
            uni.hideLoading();
            
            console.log('删除API响应:', response);
            if (response.statusCode === 200) {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              console.log('删除成功，刷新未上架活动列表');
              // 刷新未上架活动列表
              await loadOfflineActivities();
            } else {
              console.log('API请求失败或返回数据格式不正确');
              uni.showToast({
                title: '删除失败，请稍后重试',
                icon: 'none'
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error('删除活动失败:', error);
            console.log('错误详情:', error);
            uni.showToast({
              title: '删除失败，请稍后重试',
              icon: 'none'
            });
          }
        }
      }
    });
  }
};
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #eaeaea;
  padding: 0 20rpx;
}

.back-btn {
  width: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

.publish-btn {
  width: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.publish-text {
  font-size: 32rpx;
  color: #007aff;
}

.activity-list-container {
  padding-bottom: 100rpx;
}

/* Tab切换样式 */
.tab-container {
  display: flex;
  border-bottom: 1px solid #eaeaea;
  background-color: #ffffff;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 32rpx;
  color: #666666;
  position: relative;
}

.tab-item.active {
  color: #007aff;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #007aff;
  border-radius: 3rpx;
}

/* 活动列表样式 */
.activity-list {
  padding: 20rpx;
}

.list-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.activity-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.activity-info {
  flex: 1;
}

.activity-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.review-status {
  font-size: 24rpx;
  padding: 2rpx 12rpx;
  border-radius: 10rpx;
}

.status-reviewing {
  color: #ff9500;
  background-color: #fff0e0;
}

.status-approved {
  color: #4cd964;
  background-color: #e0f7e0;
}

.status-rejected {
  color: #ff3b30;
  background-color: #ffe0e0;
}

.activity-time {
  font-size: 24rpx;
  color: #999999;
}

.activity-action {
  margin-left: 20rpx;
}

.btn-download,
.btn-publish,
.btn-delete {
  font-size: 28rpx;
  padding: 0 20rpx;
  height: 60rpx;
  line-height: 60rpx;
}

.btn-download {
  background-color: #007aff;
  color: #ffffff;
}

.btn-publish {
  background-color: #4cd964;
  color: #ffffff;
}

.btn-delete {
  background-color: #ff3b30;
  color: #ffffff;
}

/* 底部发布按钮样式 - 可以考虑移除或保留 */
.publish-btn-container {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
}

.publish-btn-container .publish-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 36rpx;
  background-color: #ff9500;
  color: #ffffff;
  border-radius: 44rpx;
}
</style>